<!--

-->
<template>
    <div class="PermissionList">
        <div v-for="item in list" :key="item.id" class="row">
            <el-input v-if="edit" v-model="item.value" placeholder="填写接口地址 /api/模块/方法" @change="val => onChange(item, val)"/>
            <div v-else style="flex: 1;">{{item.value}}</div>
            <el-button link size="small" type="danger" @click="removeP(item)">移除</el-button>
        </div>
        <el-button v-if="edit" plain size="small" type="primary" @click="addP">添加权限</el-button>
        <el-button v-else plain size="small" type="primary" @click="edit=true">编辑权限</el-button>
        <el-button v-if="edit" size="small" type="primary" @click="ok">确定</el-button>
    </div>
</template>

<script>
import * as uuid from "uuid"

export default {
    name: "PermissionList",
    emits: ["update:modelValue"],
    props: {
        modelValue: {
            type: String,
            default: () => ""
        }
    },
    data() {
        return {
            list: [],
            edit: true
        }
    },
    watch: {
        modelValue() {
            this.setNormal()
        }
    },
    mounted() {
        this.setNormal()
    },
    methods: {
        setNormal() {
            const modelValue = this.modelValue;
            if (modelValue) {
                const list = modelValue.split("|").filter(item => item).map(item => {
                    return {
                        value: item,
                        id: uuid.v4()
                    }
                });
                this.list = list;
            }
        },
        onChange(item, val) {
            if (!val) return;
            const index = this.list.findIndex(t => t.id == item.id);
            if (index > -1) {
                this.list[index].value = val.replace("api", "").replace(/\//g, ":").replace("::", "");
            }

        },
        addP() {
            this.list.push({
                value: null,
                id: uuid.v4()
            })
        },
        removeP(item) {
            const index = this.list.findIndex(t => t.id == item.id);
            this.list.splice(index, 1);
            this.updateValue()
        },
        updateValue() {
            const list = this.list.filter(item => item.value).map(item => item.value).join("|");
            this.$emit("update:modelValue", list)
        },
        ok() {
            this.list = this.list.filter(item => item.value);
            this.edit = false;
            this.updateValue()
        }
    }
}
</script>

<style lang="scss" scoped>
.PermissionList {
    width: 100%;

    .row {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        padding-bottom: 4px;
    }
}
</style>
